package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	waitBySleep()
	waitByChannel()
	waitByWaitGroup()
}

//waitBySleep sleep 等待所有协程跑完再结束main,但是该等待多久呢
func waitBySleep() {
	for i := 0; i < 100; i++ {
		go fmt.Println(i)
	}
	time.Sleep(time.Second)
}

//waitByChannel
func waitByChannel() {
	c := make(chan int, 100)
	for i := 0; i < 100; i++ {
		// 这个i要但当成参数传进来，不然会出现好多好多一样的值，因为主线程的i增加1，cpu切换，协程可以跑好多个，
		// 当然，主协程还是会在协程跑完之后再执行
		go func(i int) {
			fmt.Println(i)
			c <- i
		}(i)
	}

	for i := 0; i < 100; i++ {
		<-c
	}
}

func waitByWaitGroup() {
	group := &sync.WaitGroup{}
	group.Add(100)
	for i := 0; i < 100; i++ {
		go func(i int) {
			fmt.Println(i)
			group.Done()
		}(i)
	}

	group.Wait()
}
